from django.shortcuts import render,get_object_or_404
from django.utils.text import slugify
from django.http import HttpResponse
import re
import markdown
from markdown.extensions.toc import TocExtension
from .models import Post,Category,Tag

# Create your views here.
#博客首页
def index(request):
    #return HttpResponse("欢迎来到我的博客首页")
    post_list = Post.objects.all().order_by("-created_time")
    return render(request,'blog/index.html',context={'post_list':post_list})

#博客详情
def detail(request,pk):
    post = get_object_or_404(Post,pk=pk)
    # post.body = markdown.markdown(post.body,extensions=['markdown.extensions.extra',
    #                                                     'markdown.extensions.codehilite',
    #                                                     'markdown.extensions.toc',
    #                                                     ])
    md = markdown.Markdown(extensions=['markdown.extensions.extra',
                                       'markdown.extensions.codehilite',
                                       # 'markdown.extensions.toc',
                                       TocExtension(slugify=slugify)
                                       ])
    post.body = md.convert(post.body)
    m = re.search(r'<div class="toc">\s*<ul>(.*)</ul>\s*</div>', md.toc, re.S)
    post.toc = m.group(1) if m is not None else ''
    return render(request,'blog/detail.html',context={'post':post})


#博客归档
def archive(request,year,month):
    post_list = Post.objects.filter(created_time__year=year,
                                    created_time__month=month,
                                    ).order_by('-created_time')
    return render(request,'blog/index.html',context={'post_list':post_list})

#博客分类
def category(request,pk):
    category = get_object_or_404(Category,pk=pk)
    post_list = Post.objects.filter(category=category).order_by('-created_time')
    return render(request,'blog/index.html',context={'post_list':post_list})


#博客标签
def tag(request,pk):
    tag = get_object_or_404(Tag,pk=pk)
    post_list = Post.objects.filter(tag=tag).order_by('-created_time')
    return render(request,'blog/index.html',context={'post_list':post_list})
